<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <div class="subtitle t10"><span />基础信息</div>
          <a-col :span="12">
            <a-form-item label="果树编号" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-input disabled v-decorator="['number', validatorRules.number]" placeholder="选择果园后自动生成"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="果树品种" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <j-dict-select-tag @change="changeVariety" type="list" v-decorator="['variety', validatorRules.variety]" :trigger-change="true" dictCode="txpp_tree_varieties,name,id" placeholder="请选择果树品种"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="种植时间" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <j-date @change="changePlantTime" placeholder="请选择种植时间" v-decorator="['plantTime', validatorRules.plantTime]" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="果树树龄" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-input-number disabled v-decorator="['age', validatorRules.age]" placeholder="请输入果树树龄" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属果园" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <j-dict-select-tag @change="changeOrchard" type="list" v-decorator="['orchard', validatorRules.orchard]" :trigger-change="true" dictCode="txpp_orchard,name,id" placeholder="请选择所属果园"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="果树位置" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-input v-decorator="['position']" placeholder="请输入果树位置"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="果树图片" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <j-image-upload isMultiple v-decorator="['fruitTreePictures']"></j-image-upload>
               <!-- <j-file-upload-custom
               accept="jpg,png,gif,MP4"
                listType="text"
                :uploadSize="200"
                isMultiple
                :maxLength="5"
                v-decorator="['fruitTreePictures', { rules: [{ required: true, message: '请上传果树图片' }] }]"
                tip="最多上传5张，文件大小限制200M内，文件类型支持jpg、png、gif、MP4"
                text=""
              ></j-file-upload-custom> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="果树banner" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 20px">
              <j-file-upload-custom
               accept="jpg,png,gif,MP4"
                listType="text"
                :uploadSize="200"
                isMultiple
                :maxLength="5"
                v-decorator="['banner', { rules: [{ required: true, message: '请上传果树banner' }] }]"
                tip="最多上传5张，文件大小限制200M内，文件类型支持jpg、png、gif、MP4"
                text=""
              ></j-file-upload-custom>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <div class="subtitle t10"><span />果树状态</div>
          <a-col :span="12">
            <a-form-item label="形态特征" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="300"
                :auto-size="{ minRows: 3, maxRows: 6 }" 
                v-decorator="['trait']" placeholder="请输入形态特征"
                >
              </a-textarea>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="树体状况" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="300"
                :auto-size="{ minRows: 3, maxRows: 6 }"  
                v-decorator="['treeCondition']" placeholder="请输入树体状况">
                </a-textarea>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="花穗挂果量" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="300"
                :auto-size="{ minRows: 3, maxRows: 6 }"  
                v-decorator="['fruitCount']" placeholder="请输入花穗挂果量" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="土壤要求" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="300"
                :auto-size="{ minRows: 3, maxRows: 6 }"  
                v-decorator="['soilRequirements']" placeholder="请输入土壤要求"></a-textarea>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="生长习性" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="300"
                :auto-size="{ minRows: 3, maxRows: 6 }"  
                v-decorator="['growthEnvironment']" placeholder="请输入生长习性"></a-textarea>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="气候要求" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="300"
                :auto-size="{ minRows: 3, maxRows: 6 }"  
                v-decorator="['climate']" placeholder="请输入气候要求"></a-textarea>
            </a-form-item>
          </a-col>
         <div class="subtitle t10"><span />鲜果特征</div>
          <a-col :span="12">
            <a-form-item label="鲜果规格（g/个）" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-input v-decorator="['specifications']" placeholder="请输入鲜果规格（g/个）"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="预计成熟时间" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <j-dict-select-tag type="list" v-decorator="['estimatedMaturityTime']" :trigger-change="true" dictCode="month" placeholder="请选择预计成熟时间"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="鲜果简介" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="3000"
                :auto-size="{ minRows: 3, maxRows: 6 }"  
                v-decorator="['introduce']" placeholder="请输入鲜果简介"></a-textarea>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="果子特点" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="3000"
                :auto-size="{ minRows: 3, maxRows: 6 }" 
                 v-decorator="['fruitTrait']" placeholder="请输入果子特点"></a-textarea>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="营养价值" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="3000"
                :auto-size="{ minRows: 3, maxRows: 6 }"  
                v-decorator="['nutritiveValue']" placeholder="请输入营养价值"></a-textarea>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="药材功效" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:20px">
              <a-textarea
                maxLength="3000"
                :auto-size="{ minRows: 3, maxRows: 6 }" 
                 v-decorator="['medicinalEfficacy']" placeholder="请输入药材功效"></a-textarea>
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction ,putAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDate from '@/components/jeecg/JDate'  
  import JImageUpload from '@/components/jeecg/JImageUpload'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JFileUploadCustom from '@/components/jeecg/JFileUploadCustom'

  export default {
    name: 'TxppTreeForm',
    components: {
      JFormContainer,
      JDate,
      JImageUpload,
      JDictSelectTag,
      JFileUploadCustom
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          // number: {
          //   rules: [
          //     { required: true, message: '请输入果树编号!'},
          //   ]
          // },
          variety: {
            rules: [
              { required: true, message: '请输入果树品种!'},
            ]
          },
          plantTime: {
            rules: [
              { required: true, message: '请输入种植时间!'},
            ]
          },
          age: {
            rules: [
              { required: true, message: '请输入果树树龄!'},
            ]
          },
          orchard: {
            rules: [
              { required: true, message: '请输入所属果园!'},
            ]
          },
        },
        url: {
          add: "/loquat/txppTree/add",
          edit: "/loquat/txppTree/edit",
          queryById: "/loquat/txppTree/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      changeVariety(val){
        this.getVarietyDetail(val)
      },
      changeOrchard(val){
        this.handleStatus(val)
      },
      getVarietyDetail(val) {
        getAction('/loquat/txppTreeVarieties/queryById', { id: val }).then((res) => {
          if (res.success) {
            console.log(res);
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(res.result,'banner','soilRequirements','growthEnvironment','climate','introduce','fruitTrait','nutritiveValue','medicinalEfficacy'))
          })
          }else{
            this.$message.error(res.message)
          }
        })
      },
       handleStatus(id) {
      putAction('/sys/fillRule/executeRuleByCode/tree_num_rule', { orchard: id }).then((res) => {
          if (res.success) {
            this.form.setFieldsValue({'number':res.result})
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      changePlantTime(value){
        let currDate = new Date(value.replace(/-/g, "\/")); 
        let d = new Date(); 
        let ru_year_num = d.getFullYear()-currDate.getFullYear() + 1  
        this.form.setFieldsValue({'age':ru_year_num})
      },
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'banner','info','number','variety','plantTime','age','orchard','position','fruitTreePictures','fruitTreeCharacteristics','trait','treeCondition','fruitCount','soilRequirements','growthEnvironment','climate','freshFruitCharacteristics','specifications','estimatedMaturityTime','introduce','fruitTrait','nutritiveValue','medicinalEfficacy'))
        })
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'info','number','variety','plantTime','age','orchard','position','fruitTreePictures','fruitTreeCharacteristics','trait','treeCondition','fruitCount','soilRequirements','growthEnvironment','climate','freshFruitCharacteristics','specifications','estimatedMaturityTime','introduce','fruitTrait','nutritiveValue','medicinalEfficacy'))
      },
    }
  }
</script>
<style lang="less" scoped>
.subtitle {
  color: #000;
  font-weight: 500;
  font-size: 15px;
  span {
    display: inline-block;
    width: 5px;
    height: 20px;
    background: #1890ff;
    vertical-align: middle;
    margin-right: 10px;
  }
  &.t10 {
    margin: 20px 0 30px 0;
  }
}
</style>